//
//  OAuthViewController.swift
//  Weibo
//
//  Created by 李振兴 on 15/10/16.
//  Copyright © 2015年 李振兴. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {
    
    private lazy var webView:UIWebView = UIWebView()
    // MARK: - 监听方法
    @objc private func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    /// 自动填充用户名和密码 － web 注入（以代码的方式向web页面添加内容）
    @objc private func autoFill() {
        
        let js = "document.getElementById('userId').value = '18513585825';" +
        "document.getElementById('passwd').value = 'cxy10086';"
        
        // 让 webView 执行 js
        webView.stringByEvaluatingJavaScriptFromString(js)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
       
    }
    
    override func loadView() {
        title = "登录新浪微博"
        self.view = webView
        webView.delegate = self
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
        webView.loadRequest(NSURLRequest(URL: NetWorkTools.sharedTools.oAuthURL))
    }

    deinit{
        print("oAuthView挂了")
    }
}
extension OAuthViewController:UIWebViewDelegate{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let url = request.URL where url.host == "www.huanqiu.com" else{
            return true
        }
        guard let query = url.query where query.hasPrefix("code=") else{
            print("quxiao")
            close()
            return false
        }
        let code = query.substringFromIndex("code=".endIndex)
        
        UserAccountViewModel.sharedUserAccount.loadAccessToken(code) { (isSuccess) -> () in
            if isSuccess {
                
                print("成功")
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    SVProgressHUD.dismiss()
                    NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: "welcome")
                })
                
            }else{
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                delay(0.5) { self.close() }
                print("出错")
            }
        }
        return true
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}